import helpers from './helpers.js'

export default {
	outputFinalImage: function (
		renderedImageMasks,
		outputCanvas,
		userPetCanvas = null,
		userPetLandmarks = null
	) {
		this.renderFromAPI(
			outputCanvas,
			userPetCanvas,
			userPetLandmarks,
			renderedImageMasks
		)
	},

	renderFromAPI: function (
		outputCanvas,
		userPetCanvas,
		userPetLandmarks,
		renderedImageMasks
	) {
		let ctx = outputCanvas.getContext('2d')

		outputCanvas.width = userPetCanvas.width
		outputCanvas.height = userPetCanvas.height

		ctx.drawImage(userPetCanvas, 0, 0)

		for (let i = 0; i < renderedImageMasks.length; i++) {
			this.drawMaskOnPet(renderedImageMasks[i], outputCanvas, userPetLandmarks)
		}
	},

	drawMaskOnPet: function (imageMask, outputCanvas, userPetLandmarks = null) {
		let ctx = outputCanvas.getContext('2d')
		let landmarks
		let width

		landmarks = userPetLandmarks

		if (imageMask.id != 'mouth') {
			width = Math.round(1.6 * landmarks.occularWidth)
		} else {
			width = Math.round(2 * landmarks.occularWidth)
		}

		let height = width
		let rollAngle = helpers.getRollAngle(
			landmarks.coordinates.eyeLeft.position.x,
			landmarks.coordinates.eyeLeft.position.y,
			landmarks.coordinates.eyeRight.position.x,
			landmarks.coordinates.eyeRight.position.y
		)

		let rotatedMask = helpers.rotateCanvas(imageMask.maskOutput, -rollAngle)

		ctx.drawImage(
			rotatedMask,
			0,
			0,
			Math.round(imageMask.width),
			Math.round(imageMask.height),
			Math.round(landmarks.coordinates[imageMask.id].position.x - width / 2),
			Math.round(landmarks.coordinates[imageMask.id].position.y - height / 2),
			Math.round(width),
			Math.round(height)
		)

		rotatedMask = null
	},
}
